//
//  UIColor+GColor.m
//  KingDraw
//
//  Created by Mask on 2018/5/16.
//  Copyright © 2018年 Mask. All rights reserved.
//

#import "UIColor+GColor.h"

@implementation UIColor (GColor)

/**
 十六进制颜色转为uicolor
 
 @param hexString @“#ffffffff”
 @return UIColor
 
 */
+ (UIColor *)colorFromHex:(NSString *)hexString{
    if (hexString.length==0) {
        return nil;
    }
    if ([hexString rangeOfString:@"#"].location!=NSNotFound) {
        hexString=[[hexString componentsSeparatedByString:@"#"] lastObject];
    }
    if ([hexString rangeOfString:@"0x"].location!=NSNotFound) {
        hexString=[[hexString componentsSeparatedByString:@"0x"] lastObject];
    }
    unsigned int red=0,green=0,blue=0,alpha=255;
    if (hexString.length==6) {
        NSRange range;
        range.length = 2;
        range.location = 0;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&red];
        range.location = 2;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&green];
        range.location = 4;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&blue];
    }else if (hexString.length==8){
        NSRange range;
        range.length = 2;
        range.location = 2;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&red];
        range.location = 4;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&green];
        range.location = 6;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&blue];
        range.location = 0;
        [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&alpha];
    }
    return [UIColor colorWithRed:(CGFloat)(red/255.0f) green:(CGFloat)(green / 255.0f) blue:(CGFloat)(blue / 255.0f) alpha:(CGFloat)(alpha / 255.0f)];
}

+ (UIColor *)colorFromHex:(NSString *)hexString alpha:(float)alpha{
    if (hexString.length==0) {
        return nil;
    }
    hexString=[[hexString componentsSeparatedByString:@"#"] lastObject];
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    range.location = 0;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&red];
    range.location = 2;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&green];
    range.location = 4;
    [[NSScanner scannerWithString:[hexString substringWithRange:range]]scanHexInt:&blue];
    return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green / 255.0f) blue:(float)(blue / 255.0f)alpha:alpha];
}

@end
